/*
 *  Copyright (C) 2010 michael
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 *
 * @author michael
 */

package dakside.hacc.modules.financial.exrateman;


import dakside.hacc.core.config.Configuration;
import dakside.hacc.core.dao.CurrencyDAO;
import org.dakside.utils.DateTimeHelper;
import dakside.hacc.core.models.Currency;
import dakside.hacc.core.models.ExchangeRate;
import dakside.hacc.core.models.ExchangeRateType;
import dakside.hacc.modules.financial.currencyman.CurrencyManager;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;

/**
 *
 * @author michael
 */
public class ExchangeRateManageView extends javax.swing.JPanel {
    private ExchangeRate[] result;
    public static final String ALL_STR = "All";
    /** Creates new form ExchangeRateManageView */
    public ExchangeRateManageView() {
        initComponents();
        initSamples();
        load();
        initTable(tblResult);        
    }

    public void setResult(ExchangeRate[] result){
        this.result = result;
    }

    //TODO put this into auto initial setup
    private void initSamples(){
        try{
            ExchangeRateManager manager = ExchangeRateManager.getInstance();
            ExchangeRateType[] types = manager.getAllExchangeRateTypes();
            if (types==null || types.length == 0){
                manager.save(new ExchangeRateType("User",0));
                manager.save(new ExchangeRateType("Imported",1));
                manager.save(new ExchangeRateType("Service",2));
            }

            ExchangeRate[] rates = manager.getAllExchangeRates();
            CurrencyDAO curDAO = Configuration.getInstance().getDAOFactory().getCurrencyDAO();
            Currency sgd = curDAO.getCurrency("SGD");
            Currency vnd = curDAO.getCurrency("VND");

            ExchangeRateType[] tps = manager.getAllExchangeRateTypes();
            if (tps == null || tps.length == 0) return;
            if (rates==null || rates.length == 0){
                manager.save(new ExchangeRate(sgd,vnd,new Date(), new Date(),  13543, tps[0]));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

   
    private void load(){
        try{
            ExchangeRateManager rateManager = ExchangeRateManager.getInstance();
            CurrencyManager curManager = CurrencyManager.getInstance();
            Currency[] allCur = curManager.getAllCurrency();

            //load from currency combo
            DefaultComboBoxModel modelComboFromCur = (DefaultComboBoxModel)(comboFromCur.getModel());
            modelComboFromCur.addElement(ALL_STR);
            for (Currency cur:allCur){
                modelComboFromCur.addElement(cur);
            }

            //load to currency combo
            DefaultComboBoxModel modelComboToCur = (DefaultComboBoxModel)(comboToCur.getModel());
            modelComboToCur.addElement(ALL_STR);
            for (Currency cur:allCur){
                modelComboToCur.addElement(cur);
            }

            //load dates
            txtFromDate.setText(DateTimeHelper.toString(DateTimeHelper.toDateStart(new Date()),"dd/mm/yyyy HH:mm:ss"));
            txtToDate.setText(DateTimeHelper.toString(DateTimeHelper.toDateEnd(new Date()),"dd/mm/yyyy HH:mm:ss"));

            //load types
            DefaultComboBoxModel modelComboType = (DefaultComboBoxModel)(comboType.getModel());
            ExchangeRateType[] allTypes = rateManager.getAllExchangeRateTypes();
            modelComboType.addElement(ALL_STR);
            for (ExchangeRateType typ:allTypes){
                modelComboType.addElement(typ);
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        

    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        comboFromCur = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtFromDate = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        comboType = new javax.swing.JComboBox();
        btnSearch = new javax.swing.JButton();
        jLabel16 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        comboToCur = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        txtToDate = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblResult = new javax.swing.JTable();
        btnDelete = new javax.swing.JButton();

        jPanel2.setName("jPanel2"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jPanel3.setName("jPanel3"); // NOI18N

        jLabel1.setText("From");
        jLabel1.setName("jLabel1"); // NOI18N

        comboFromCur.setName("comboFromCur"); // NOI18N

        jLabel3.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jLabel3.setText("Currency");
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jLabel4.setText("Date");
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText("From");
        jLabel5.setName("jLabel5"); // NOI18N

        txtFromDate.setText("jTextField1");
        txtFromDate.setName("txtFromDate"); // NOI18N

        jLabel7.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jLabel7.setText("Type");
        jLabel7.setName("jLabel7"); // NOI18N

        comboType.setName("comboType"); // NOI18N

        btnSearch.setText("Search");
        btnSearch.setName("btnSearch"); // NOI18N
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        jLabel16.setText("(dd/mm/yyyy)");
        jLabel16.setName("jLabel16"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(ExchangeRateManageView.class, this);
        jButton1.setAction(actionMap.get("btnCreateNewActionPerformed")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboFromCur, 0, 175, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel16))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtFromDate, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboType, 0, 173, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(btnSearch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jLabel3))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel1)
                    .addComponent(comboFromCur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel16))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtFromDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(comboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSearch)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel4.setName("jPanel4"); // NOI18N

        jLabel2.setText("To");
        jLabel2.setName("jLabel2"); // NOI18N

        comboToCur.setName("comboToCur"); // NOI18N

        jLabel6.setText("To");
        jLabel6.setName("jLabel6"); // NOI18N

        txtToDate.setText("jTextField2");
        txtToDate.setName("txtToDate"); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboToCur, 0, 189, Short.MAX_VALUE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(txtToDate, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboToCur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtToDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(91, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblResult.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblResult.setName("tblResult"); // NOI18N
        jScrollPane1.setViewportView(tblResult);

        btnDelete.setAction(actionMap.get("btnDeleteActionPerformed")); // NOI18N
        btnDelete.setName("btnDelete"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)
                    .addComponent(btnDelete))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnDelete)
                .addGap(62, 62, 62))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(34, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        try{
            ExchangeRateManager manager = ExchangeRateManager.getInstance();

            CurrencyManager curManager = CurrencyManager.getInstance();
            Date fromDate = DateTimeHelper.toDate(txtFromDate.getText().trim());
            Date toDate = DateTimeHelper.toDate(txtToDate.getText().trim());

            Currency fromCur = null;
            Object objFromCur = comboFromCur.getSelectedItem();
            
            if(objFromCur instanceof Currency){
                fromCur = (Currency)objFromCur;
            }

            Currency toCur = null;
            Object objToCur = comboToCur.getSelectedItem();            
            if(objToCur instanceof Currency){
                toCur = (Currency)objToCur;
            }

            ExchangeRateType type = null;
            Object objType = comboType.getSelectedItem();            
            if(objType instanceof ExchangeRateType){
                type = (ExchangeRateType)objType;
            }


            ExchangeRate[] results = manager.getExchangeRatesByCriteria(fromCur, toCur, fromDate, toDate, type);
            
            //update result global table for delete function
            setResult(results);

            System.out.println("Exchange rates found: " + results.length);
            DefaultTableModel model = new DefaultTableModel();
            model.setColumnIdentifiers(new Object[] {"Start","End","From","To","Type","Rates"});
            tblResult.setModel(model);

            loadTable(results,tblResult);
        }catch(Exception ex){
            ex.printStackTrace();
        }
}//GEN-LAST:event_btnSearchActionPerformed


    private void loadTable(ExchangeRate[] rates, javax.swing.JTable table){
        if(rates == null || rates.length == 0) return;
        DefaultTableModel model = (DefaultTableModel)table.getModel();
        for (ExchangeRate rate:rates){
            model.addRow(new Object[] {rate.getFromCurrency(),rate.getToCurrency(),DateTimeHelper.toStringSmart(rate.getFromDate()),DateTimeHelper.toStringSmart(rate.getToDate()),rate.getType(),rate.getRate()});
        }
    }

    private void initTable(javax.swing.JTable table){
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(new Object[] {"Start","End","From","To","Type","Rates"});
        table.setModel(model);
    }

    @Action
    public void btnCreateNewActionPerformed(java.awt.event.ActionEvent evt) {
        
        NewExchangeRateDialog dialog = new NewExchangeRateDialog(null,true);
        if(dialog.getReturnStatus() == 0){
            System.out.println("Unable to save exchange rate");
        }else{
            System.out.println("Save successfully");
        }
    }

    @Action
    public void btnDeleteActionPerformed() {
        int pos = tblResult.getSelectedRow();
        System.out.println("pos: " + pos);
        if (pos < 0 || pos >= result.length){
            System.out.println("Invalid selected index");
        }else{
            System.out.println("Remove rate");
            ExchangeRate rate = result[pos];
            ExchangeRateManager manager = ExchangeRateManager.getInstance();
            manager.delete(rate);
            //remove row from table
            DefaultTableModel model = (DefaultTableModel)tblResult.getModel();
            model.removeRow(pos);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnSearch;
    private javax.swing.JComboBox comboFromCur;
    private javax.swing.JComboBox comboToCur;
    private javax.swing.JComboBox comboType;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblResult;
    private javax.swing.JTextField txtFromDate;
    private javax.swing.JTextField txtToDate;
    // End of variables declaration//GEN-END:variables

}
